package danny.hoi.exam.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import danny.hoi.exam.domain.Users;
import danny.hoi.exam.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class UsersController {
    @Reference
    private UsersService usersService;
    @Autowired
    private HttpServletRequest request;


    /**
     * 分页显示所有用户
     * 请求地址：/user/findAll.do
     * 响应地址：WEB-INF/pages/user/user-list.jsp
     */
    @RequestMapping("/findAll")
    public String findAll(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "5") Integer pageSize) {
        PageInfo<Users> pageInfo = usersService.findByPages(page, pageSize);
        request.setAttribute("pageInfo", pageInfo);
        return "user/user-list";
    }

    /**
     * 访问新建用户
     * 请求地址：/user/toAdd.do
     * 响应地址：WEB-INF/pages/user/user-edit.jsp
     */
    @RequestMapping("/toAdd")
    public String toEdit() {
        return "user/user-edit";
    }

    /**
     * 访问修改用户页面
     * 请求地址：/user/toUpdate.do?id=${item.id}
     * 响应地址：WEB-INF/pages/user/user-edit.jsp
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        Users user = usersService.findById(id);
        request.setAttribute("user", user);
        return "user/user-edit";
    }

    /**
     * 添加用户/修改用户
     * 请求地址：/user/edit.do
     * 响应地址：/user/findAll.do
     */
    @RequestMapping("/edit")
    public String edit(Users users) {
        if (StringUtils.isEmpty(users.getId())) {
            //添加
            usersService.save(users);
        } else {
            //修改
            usersService.update(users);
        }
        //重定向到列表页面
        return "redirect:/user/findAll.do";
    }

}
